<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Switch - A switch statement for Perl, do not use if you can use given/when - metacpan.org</title>
        <link rel="preload" as="fetch" href="https://metacpan.org/account/login_status" crossorigin="anonymous" />
        <link href="https://metacpan.org/_assets/b8ccceeed47a0652049703d99326a9cea4933443.css" rel="stylesheet" type="text/css">
        <script src="https://metacpan.org/_assets/6bfedafe2d7caa915b7d84f61b45936818e3242e.js" type="text/javascript" defer></script>
        <link rel="alternate" type="application/rss+xml" title="Recent CPAN Uploads of Switch - MetaCPAN" href="https://metacpan.org/dist/Switch/releases.rss" />
        <link rel="canonical" href="Switch.html" />
        <meta name="description" content="A switch statement for Perl, do not use if you can use given/when" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5">
        <link rel="shortcut icon" href="https://metacpan.org/static/icons/favicon.ico">
        <link rel="apple-touch-icon" sizes="152x152" href="https://metacpan.org/static/icons/apple-touch-icon.png">
        <link rel="search" href="https://metacpan.org/static/opensearch.xml" type="application/opensearchdescription+xml" title="MetaCPAN">
        <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

          (function(skey, ga_id){
            ga('create', ga_id, {
              siteSpeedSampleRate : 100,
              storage             : 'none',
              clientId            : localStorage.getItem(skey)
            });
            ga(function(tracker) {
              localStorage.setItem(skey, tracker.get('clientId'));
            });
            ga('send', 'pageview');
          })('ga:clientId', 'UA-27829474-1');
        </script>
<meta name="twitter:card"        content="summary" />
<meta name="twitter:url"         content="https://metacpan.org/pod/Switch" />
<meta name="twitter:title"       content="Switch" />
<meta name="twitter:description" content="A switch statement for Perl, do not use if you can use given/when" />
<meta name="twitter:site"        content="metacpan" />
    </head>
    <body>
        <nav class="navbar navbar-default" role="navigation">
            <div class="header-logo-large hidden-xs">
              <a href="https://metacpan.org/" tabindex="0">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#logo" />
                </svg>
              </a>
            </div>
            <div class="header-logo-icon visible-xs">
              <a href="https://metacpan.org/">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#dots" />
                </svg>
              </a>
            </div>
            <ul class="nav navbar-nav menu-items hidden-xs hidden-sm">
              <li><a href="https://metacpan.org/about">About</a></li>
              <li><a href="https://metacpan.org/about/sponsors">Sponsor</a></li>
              <li><a href="https://grep.metacpan.org/">grep::cpan</a></li>
              <li><a href="https://metacpan.org/recent">Recent</a></li>
              <li><a href="https://metacpan.org/about/faq">FAQ</a></li>
              <li><a href="https://metacpan.org/tools">Tools</a></li>
              <li><a href="https://fastapi.metacpan.org/">API</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <button type="button" class="searchbar-btn visible-xs visible-sm">
                    <i class="fa fa-search button-fa-icon"></i>
                </button>
                <form action="https://metacpan.org/search" class="searchbar-form visible-md visible-lg search-form form-horizontal">
                   <input type="hidden" name="size" id="metacpan_search-size" value="20">
                  <div class="form-group">
                      <div class="search-group">
                        <i class="fa fa-search"></i>
                        <input type="text" name="q" placeholder="Search the CPAN" size="41" autocorrect="off" autocapitalize="off" spellcheck="false" id="metacpan_search-input" class="form-control" value="">
                      </div>
                  </div>
                </form>
                    <li class="icon-slidepanel visible-xs visible-sm">
                      <button data-toggle="slidepanel" data-target=".slidepanel">
                        <span class="button-fa-icon">
                          <i class="fa fa-bars slidepanel-open"></i>
                          <i class="fa fa-times slidepanel-close"></i>
                        </span>
                      </button>
                    </li>
                <form action="https://metacpan.org/account/logout" method="POST" id="metacpan-logout"></form>
                <li class="dropdown logged_in" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon logged-in-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a href="https://metacpan.org/account/identities">Identities</a></li>
                        <li><a href="https://metacpan.org/account/profile">Profile</a></li>
                        <li><a href="https://metacpan.org/account/favorite/list">Favorites</a></li>
                        <li>
                            <a href="Switch.html#" type="button" onclick="$('#metacpan-logout').submit(); return false">
                              Logout
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_out" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a href="https://metacpan.org/login/github">
                                <i class="fab fa-github fa-fw"></i>
                                GitHub
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/twitter">
                                <i class="fab fa-twitter fa-fw"></i>
                                Twitter
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/google">
                                <i class="fab fa-google fa-fw"></i>
                                Google
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_placeholder">
                    <button>
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                    </button>
                </li>
            </ul>
        </nav>
        <div class="page-content ">
          <!--
          <div class="top-notify-banner">
            <i class="fas fa-info-circle"></i>
          </div>
          -->
          <nav class="sidebar">
            <div class="slidepanel">
              <ul class="nav-list ">
    <li class="nav-header no-margin-top">
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The date that this version of Switch was released.">
      <span class="relatize">18 Mar 2014 12:30:25 UTC</span>
    </li>
  <li>
    Distribution: <a href="https://metacpan.org/dist/Switch">Switch</a>
  </li>
  <li>
    Module version: 2.17
  </li>
  <li>
    <a data-keyboard-shortcut="g s" href="https://metacpan.org/dist/Switch/source/Switch.pm">Source</a>
    (<a href="https://metacpan.org/dist/Switch/source/Switch.pm?raw=1">raw</a>)
  </li>
  <li>
    <a data-keyboard-shortcut="g b" href="https://metacpan.org/dist/Switch/source">Browse</a>
    (<a href="https://metacpan.org/dist/Switch/source?raw=1">raw</a>)
  </li>
    <li>
      <a data-keyboard-shortcut="g c" href="https://metacpan.org/dist/Switch/changes">Changes</a>
    </li>
    <li>
      <a class="nopopup" href="https://metacpan.org/dist/Switch/contribute">How to Contribute</a>
    </li>
    <li>
        <a rel="noopener nofollow" data-keyboard-shortcut="g r" href="https://github.com/chorny/Switch">Repository</a>
    </li>
    <li>
      <a rel="noopener nofollow" data-keyboard-shortcut="g i" href="https://rt.cpan.org/Public/Dist/Display.html?Name=Switch">Issues</a>
      (12)
    </li>
    <li>
      <a rel="noopener nofollow" href="http://matrix.cpantesters.org/?dist=Switch+2.17" title="Matrix">Testers</a>
        <span title="(pass / fail / na)">(<a rel="noopener nofollow" href="https://www.cpantesters.org/distro/S/Switch.html?oncpan=1&amp;distmat=1&amp;version=2.17&amp;grade=2" style="color: #090">529</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/S/Switch.html?oncpan=1&amp;distmat=1&amp;version=2.17&amp;grade=3" style="color: #900">3</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/S/Switch.html?oncpan=1&amp;distmat=1&amp;version=2.17&amp;grade=4">0</a>)</span>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpants.cpanauthors.org/release/CHORNY/Switch-2.17">Kwalitee</a>
    </li>
    <li>
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The # people with an indexing permission on Switch who have released something to CPAN in the last 2 years (i.e. the # people likely able to release critical fixes in a timely manner)">
      Bus factor: 1
      </div>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpancover.com/latest/Switch-2.17/index.html">67.33% Coverage </a>
    </li>
    <li>
      License: perl_5
    </li>
    <li>
      Perl: v5.5.0
    </li>
    <li class="nav-header">Activity</li>
    <li>
<div class="activity-graph">
    <img src="https://metacpan.org/dist/Switch/activity.svg?res=month" />
    <div class="comment">24 month</div>
</div>
    </li>
    <li class="nav-header">Tools</li>
    <li>
      <a itemprop="downloadUrl" href="https://cpan.metacpan.org/authors/id/C/CH/CHORNY/Switch-2.17.tar.gz">
      Download (<span itemprop="fileSize">14.15KB</span>)</a>
    </li>
    <li>
      <a href="https://explorer.metacpan.org/?url=%2Fmodule%2FCHORNY%2FSwitch-2.17%2FSwitch.pm">
        MetaCPAN Explorer
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/Switch/permissions">
        Permissions
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/Switch/releases.rss">
        Subscribe to distribution
      </a>
    </li>
    <li>
      <button class="btn btn-link" data-toggle="modal" data-target="#metacpan_install-instructions-dialog">
        Install Instructions
      </button>
    </li>
    <li>
      <form action="https://metacpan.org/search">
        <input type="hidden" name="q" value="dist:Switch">
        <input type="search" name="q" placeholder="Search distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
      </form>
    </li>
    <li>
      <form action="https://grep.metacpan.org/search">
        <input type="hidden" name="qd" value="Switch">
        <input type="hidden" name="source" value="metacpan">
        <input type="search" name="q" placeholder="grep distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
     </form>
    </li>
    <li class="version-jump">
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/Switch.pm&#39;" class="form-control tool-bar-form">
  <option disabled selected>Jump to version</option>
<option
  disabled
  value="CHORNY/Switch-2.17"
>2.17
  (CHORNY on 2014-03-18)</option>
<option
  
  value="RGARCIA/Switch-2.16"
>2.16
  (RGARCIA on 2009-10-23)</option>
<option
  
  value="RGARCIA/Switch-2.15"
>2.15
  (RGARCIA on 2009-10-20)</option>
<option
  
  value="RGARCIA/Switch-2.14"
>2.14
  (RGARCIA on 2008-12-29)</option>
<option
  
  value="RGARCIA/Switch-2.13"
>2.13
  (RGARCIA on 2007-02-25)</option>
<option
  
  value="RGARCIA/Switch-2.12"
>2.12
  (RGARCIA on 2006-12-11)</option>
<option
  
  value="RGARCIA/Switch-2.11"
>2.11
  (RGARCIA on 2006-11-22)</option>
<option
  
  value="RGARCIA/Switch-2.10"
>2.10
  (RGARCIA on 2004-01-28)</option>
<option
  
  value="DCONWAY/Switch-2.09"
>2.09
  (DCONWAY on 2002-06-12)</option>
<optgroup label="BackPAN">'
<option
  
  value="DCONWAY/Switch-2.07"
>2.07
  (DCONWAY on 2002-05-15)</option>
<option
  
  value="DCONWAY/Switch-2.06"
>2.06
  (DCONWAY on 2001-11-14)</option>
<option
  
  value="DCONWAY/Switch-2.05"
>2.05
  (DCONWAY on 2001-09-02)</option>
<option
  
  value="DCONWAY/Switch-2.04"
>2.04
  (DCONWAY on 2001-07-30)</option>
<option
  
  value="DCONWAY/Switch-2.03"
>2.03
  (DCONWAY on 2001-05-14)</option>
<option
  
  value="DCONWAY/Switch-2.02"
>2.02
  (DCONWAY on 2001-04-26)</option>
<option
  
  value="DCONWAY/Switch-2.01"
>2.01
  (DCONWAY on 2001-01-08)</option>
<option
  
  value="DCONWAY/Switch-2.00"
>2.00
  (DCONWAY on 2001-01-08)</option>
<option
  
  value="DCONWAY/Switch-1.00"
>1.00
  (DCONWAY on 2000-08-07)</option>
</optgroup>
</select>
    </li>
    <li class="version-diff">
<select onchange="document.location.href='/release/CHORNY/Switch-2.17/diff/' + encodeURIComponent(this.value) + '/Switch.pm'
" class="form-control tool-bar-form">
  <option disabled selected>Diff with version</option>
<option
  disabled
  value="CHORNY/Switch-2.17"
>2.17
  (CHORNY on 2014-03-18)</option>
<option
  
  value="RGARCIA/Switch-2.16"
>2.16
  (RGARCIA on 2009-10-23)</option>
<option
  
  value="RGARCIA/Switch-2.15"
>2.15
  (RGARCIA on 2009-10-20)</option>
<option
  
  value="RGARCIA/Switch-2.14"
>2.14
  (RGARCIA on 2008-12-29)</option>
<option
  
  value="RGARCIA/Switch-2.13"
>2.13
  (RGARCIA on 2007-02-25)</option>
<option
  
  value="RGARCIA/Switch-2.12"
>2.12
  (RGARCIA on 2006-12-11)</option>
<option
  
  value="RGARCIA/Switch-2.11"
>2.11
  (RGARCIA on 2006-11-22)</option>
<option
  
  value="RGARCIA/Switch-2.10"
>2.10
  (RGARCIA on 2004-01-28)</option>
<option
  
  value="DCONWAY/Switch-2.09"
>2.09
  (DCONWAY on 2002-06-12)</option>
<optgroup label="BackPAN">'
<option
  
  value="DCONWAY/Switch-2.07"
>2.07
  (DCONWAY on 2002-05-15)</option>
<option
  
  value="DCONWAY/Switch-2.06"
>2.06
  (DCONWAY on 2001-11-14)</option>
<option
  
  value="DCONWAY/Switch-2.05"
>2.05
  (DCONWAY on 2001-09-02)</option>
<option
  
  value="DCONWAY/Switch-2.04"
>2.04
  (DCONWAY on 2001-07-30)</option>
<option
  
  value="DCONWAY/Switch-2.03"
>2.03
  (DCONWAY on 2001-05-14)</option>
<option
  
  value="DCONWAY/Switch-2.02"
>2.02
  (DCONWAY on 2001-04-26)</option>
<option
  
  value="DCONWAY/Switch-2.01"
>2.01
  (DCONWAY on 2001-01-08)</option>
<option
  
  value="DCONWAY/Switch-2.00"
>2.00
  (DCONWAY on 2001-01-08)</option>
<option
  
  value="DCONWAY/Switch-1.00"
>1.00
  (DCONWAY on 2000-08-07)</option>
</optgroup>
</select>
    </li>

    <li>
<ul class="dependencies">
  <li class="nav-header">Dependencies</li>
  <li><a href="https://metacpan.org/pod/Filter::Util::Call" title="Filter::Util::Call" class="ellipsis">Filter::Util::Call</a></li>
  <li><a href="https://metacpan.org/pod/Text::Balanced" title="Text::Balanced" class="ellipsis">Text::Balanced</a></li>
  <li><a href="https://metacpan.org/pod/if" title="if" class="ellipsis">if</a></li>
  <li><i class="ttip" title="dynamic_config enabled">and possibly others</i></li>
  <li>
    <hr>
  </li>
  <li>
    <a href="https://metacpan.org/module/Switch/requires">Reverse dependencies</a>
  </li>
  <li>
    <a href="http://deps.cpantesters.org/?module=Switch">CPAN Testers List</a>
  </li>
  <li>
    <a href="https://cpandeps.grinnz.com/?dist=Switch">Dependency graph</a>
  </li>
</ul>
    </li>
    <li class="nav-header">Permalinks</li>
    <li>
      <a href="https://metacpan.org/release/CHORNY/Switch-2.17/view/Switch.pm">This version</a>
    </li>
    <li>
      <a href="Switch.html">Latest version</a>
    </li>
    <li>
<div class="plussers">
<div class="nav-header">++ed by:</div>
<div>
    3 non-PAUSE users
</div>
</div>
    </li>
    <li>
<div id="metacpan_contributors">
  <div>
    <button class="btn-link"
      onclick="$(this).hide(); $('#metacpan_contributors ul').slideDown(); return false;"
    >and 3 contributors</button>
  </div>
  <ul style="display: none">
    <li class="contributor"
    >
      Damian Conway
    </li>
    <li class="contributor"
    >
      Rafael Garcia-Suarez
    </li>
    <li class="contributor"
    >
      Alexandr Ciornii
    </li>
  </ul>
</div>
    </li>
              </ul>
            </div>
          </nav>
          <div class="content-navigation">
<div class="breadcrumbs">
  <span>
    <a data-keyboard-shortcut="g a" rel="author" href="https://metacpan.org/author/CHORNY" class="author-name">Alexandr Ciornii</a>
  </span>
  <span>&nbsp;/&nbsp;</span>
  <div class="release dist-release status-latest maturity-released">
    <span class="dropdown"><b class="caret"></b></span>
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/Switch.pm&#39;" class="">
<option
  selected
  value="CHORNY/Switch-2.17"
>2.17
  (CHORNY on 2014-03-18)</option>
<option
  
  value="RGARCIA/Switch-2.16"
>2.16
  (RGARCIA on 2009-10-23)</option>
<option
  
  value="RGARCIA/Switch-2.15"
>2.15
  (RGARCIA on 2009-10-20)</option>
<option
  
  value="RGARCIA/Switch-2.14"
>2.14
  (RGARCIA on 2008-12-29)</option>
<option
  
  value="RGARCIA/Switch-2.13"
>2.13
  (RGARCIA on 2007-02-25)</option>
<option
  
  value="RGARCIA/Switch-2.12"
>2.12
  (RGARCIA on 2006-12-11)</option>
<option
  
  value="RGARCIA/Switch-2.11"
>2.11
  (RGARCIA on 2006-11-22)</option>
<option
  
  value="RGARCIA/Switch-2.10"
>2.10
  (RGARCIA on 2004-01-28)</option>
<option
  
  value="DCONWAY/Switch-2.09"
>2.09
  (DCONWAY on 2002-06-12)</option>
<optgroup label="BackPAN">'
<option
  
  value="DCONWAY/Switch-2.07"
>2.07
  (DCONWAY on 2002-05-15)</option>
<option
  
  value="DCONWAY/Switch-2.06"
>2.06
  (DCONWAY on 2001-11-14)</option>
<option
  
  value="DCONWAY/Switch-2.05"
>2.05
  (DCONWAY on 2001-09-02)</option>
<option
  
  value="DCONWAY/Switch-2.04"
>2.04
  (DCONWAY on 2001-07-30)</option>
<option
  
  value="DCONWAY/Switch-2.03"
>2.03
  (DCONWAY on 2001-05-14)</option>
<option
  
  value="DCONWAY/Switch-2.02"
>2.02
  (DCONWAY on 2001-04-26)</option>
<option
  
  value="DCONWAY/Switch-2.01"
>2.01
  (DCONWAY on 2001-01-08)</option>
<option
  
  value="DCONWAY/Switch-2.00"
>2.00
  (DCONWAY on 2001-01-08)</option>
<option
  
  value="DCONWAY/Switch-1.00"
>1.00
  (DCONWAY on 2000-08-07)</option>
</optgroup>
</select>
    <a data-keyboard-shortcut="g d" class="release-name" href="https://metacpan.org/dist/Switch">Switch-2.17</a>
  </div>
<span class="river-gauge-gauge">
  <svg width="24px"
       height="15px"
       version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink">

    <g>
      <title>        River stage two &#10;
          • 24 direct dependents &#10;          • 47 total dependents
      </title>

      <rect x="0"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="5"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="10"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="15"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="20"  y="0" width="4" height="15" fill="#e4e2e2" />
    </g>
  </svg>

</span>
<div id="Switch-fav" class="logged_in">
<form action="https://metacpan.org/account/favorite/add" style="display: inline" onsubmit="return favDistribution(this)">
    <input type="hidden" name="remove" value="0">
    <input type="hidden" name="release" value="Switch-2.17">
    <input type="hidden" name="author" value="CHORNY">
    <input type="hidden" name="distribution" value="Switch">
    <button type="submit" class="favorite highlight"><span>3</span> ++</button>
</form>
</div>
<div class="logged_out">
<a href="Switch.html" onclick="alert('Please sign in to add favorites'); return false" class="favorite highlight">
<span>3</span> ++</a>
</div>
   / <span>Switch</span>
</div>
          </div>
          <main class="content">


<nav class="toc">
  <div class="toc-header"><strong>Contents</strong></div>
<ul>
  <li><a href="Switch.html#NAME">NAME</a></li>
  <li><a href="Switch.html#SYNOPSIS">SYNOPSIS</a></li>
  <li><a href="Switch.html#BACKGROUND">BACKGROUND</a></li>
  <li><a href="Switch.html#DESCRIPTION">DESCRIPTION</a>
    <ul>
      <li><a href="Switch.html#Allowing-fall-through">Allowing fall-through</a></li>
      <li><a href="Switch.html#Automating-fall-through">Automating fall-through</a></li>
      <li><a href="Switch.html#Alternative-syntax">Alternative syntax</a></li>
      <li><a href="Switch.html#Higher-order-Operations">Higher-order Operations</a></li>
    </ul>
  </li>
  <li><a href="Switch.html#DEPENDENCIES">DEPENDENCIES</a></li>
  <li><a href="Switch.html#AUTHOR">AUTHOR</a></li>
  <li><a href="Switch.html#BUGS">BUGS</a></li>
  <li><a href="Switch.html#LIMITATIONS">LIMITATIONS</a></li>
  <li><a href="Switch.html#COPYRIGHT">COPYRIGHT</a></li>
</ul></nav>
<div class="pod anchors">
<h1 id="NAME">NAME</h1>

<p>Switch - A switch statement for Perl, do not use if you can use given/when</p>

<h1 id="SYNOPSIS">SYNOPSIS</h1>

<pre><code>    use Switch;

    switch ($val) {
        case 1          { print &quot;number 1&quot; }
        case &quot;a&quot;        { print &quot;string a&quot; }
        case [1..10,42] { print &quot;number in list&quot; }
        case (\@array)  { print &quot;number in list&quot; }
        case /\w+/      { print &quot;pattern&quot; }
        case qr/\w+/    { print &quot;pattern&quot; }
        case (\%hash)   { print &quot;entry in hash&quot; }
        case (\&amp;sub)    { print &quot;arg to subroutine&quot; }
        else            { print &quot;previous case not true&quot; }
    }</code></pre>

<h1 id="BACKGROUND">BACKGROUND</h1>

<p>[Skip ahead to <a href="Switch.html#DESCRIPTION">&quot;DESCRIPTION&quot;</a> if you don&#39;t care about the whys and wherefores of this control structure]</p>

<p>In seeking to devise a &quot;Swiss Army&quot; case mechanism suitable for Perl, it is useful to generalize this notion of distributed conditional testing as far as possible. Specifically, the concept of &quot;matching&quot; between the switch value and the various case values need not be restricted to numeric (or string or referential) equality, as it is in other languages. Indeed, as Table 1 illustrates, Perl offers at least eighteen different ways in which two values could generate a match.</p>

<pre><code>        Table 1: Matching a switch value ($s) with a case value ($c)

        Switch  Case    Type of Match Implied   Matching Code
        Value   Value   
        ======  =====   =====================   =============

        number  same    numeric or referential  match if $s == $c;
        or ref          equality

        object  method  result of method call   match if $s-&gt;$c();
        ref     name                            match if defined $s-&gt;$c();
                or ref

        other   other   string equality         match if $s eq $c;
        non-ref non-ref
        scalar  scalar

        string  regexp  pattern match           match if $s =~ /$c/;

        array   scalar  array entry existence   match if 0&lt;=$c &amp;&amp; $c&lt;@$s;
        ref             array entry definition  match if defined $s-&gt;[$c];
                        array entry truth       match if $s-&gt;[$c];

        array   array   array intersection      match if intersects(@$s, @$c);
        ref     ref     (apply this table to
                         all pairs of elements
                         $s-&gt;[$i] and
                         $c-&gt;[$j])

        array   regexp  array grep              match if grep /$c/, @$s;
        ref     

        hash    scalar  hash entry existence    match if exists $s-&gt;{$c};
        ref             hash entry definition   match if defined $s-&gt;{$c};
                        hash entry truth        match if $s-&gt;{$c};

        hash    regexp  hash grep               match if grep /$c/, keys %$s;
        ref     

        sub     scalar  return value defn       match if defined $s-&gt;($c);
        ref             return value truth      match if $s-&gt;($c);

        sub     array   return value defn       match if defined $s-&gt;(@$c);
        ref     ref     return value truth      match if $s-&gt;(@$c);</code></pre>

<p>In reality, Table 1 covers 31 alternatives, because only the equality and intersection tests are commutative; in all other cases, the roles of the <code>$s</code> and <code>$c</code> variables could be reversed to produce a different test. For example, instead of testing a single hash for the existence of a series of keys (<code>match if exists $s-&gt;{$c}</code>), one could test for the existence of a single key in a series of hashes (<code>match if exists $c-&gt;{$s}</code>).</p>

<h1 id="DESCRIPTION">DESCRIPTION</h1>

<p>The Switch.pm module implements a generalized case mechanism that covers most (but not all) of the numerous possible combinations of switch and case values described above.</p>

<p>The module augments the standard Perl syntax with two new control statements: <code>switch</code> and <code>case</code>. The <code>switch</code> statement takes a single scalar argument of any type, specified in parentheses. <code>switch</code> stores this value as the current switch value in a (localized) control variable. The value is followed by a block which may contain one or more Perl statements (including the <code>case</code> statement described below). The block is unconditionally executed once the switch value has been cached.</p>

<p>A <code>case</code> statement takes a single scalar argument (in mandatory parentheses if it&#39;s a variable; otherwise the parens are optional) and selects the appropriate type of matching between that argument and the current switch value. The type of matching used is determined by the respective types of the switch value and the <code>case</code> argument, as specified in Table 1. If the match is successful, the mandatory block associated with the <code>case</code> statement is executed.</p>

<p>In most other respects, the <code>case</code> statement is semantically identical to an <code>if</code> statement. For example, it can be followed by an <code>else</code> clause, and can be used as a postfix statement qualifier.</p>

<p>However, when a <code>case</code> block has been executed control is automatically transferred to the statement after the immediately enclosing <code>switch</code> block, rather than to the next statement within the block. In other words, the success of any <code>case</code> statement prevents other cases in the same scope from executing. But see <a href="Switch.html#Allowing-fall-through">&quot;Allowing fall-through&quot;</a> below.</p>

<p>Together these two new statements provide a fully generalized case mechanism:</p>

<pre><code>        use Switch;

        # AND LATER...

        %special = ( woohoo =&gt; 1,  d&#39;oh =&gt; 1 );

        while (&lt;&gt;) {
            chomp;
            switch ($_) {
                case (%special) { print &quot;homer\n&quot;; }      # if $special{$_}
                case /[a-z]/i   { print &quot;alpha\n&quot;; }      # if $_ =~ /a-z/i
                case [1..9]     { print &quot;small num\n&quot;; }  # if $_ in [1..9]
                case { $_[0] &gt;= 10 } { print &quot;big num\n&quot;; } # if $_ &gt;= 10
                print &quot;must be punctuation\n&quot; case /\W/;  # if $_ ~= /\W/
            }
        }</code></pre>

<p>Note that <code>switch</code>es can be nested within <code>case</code> (or any other) blocks, and a series of <code>case</code> statements can try different types of matches -- hash membership, pattern match, array intersection, simple equality, etc. -- against the same switch value.</p>

<p>The use of intersection tests against an array reference is particularly useful for aggregating integral cases:</p>

<pre><code>        sub classify_digit
        {
                switch ($_[0]) { case 0            { return &#39;zero&#39; }
                                 case [2,4,6,8]    { return &#39;even&#39; }
                                 case [1,3,5,7,9]  { return &#39;odd&#39; }
                                 case /[A-F]/i     { return &#39;hex&#39; }
                               }
        }</code></pre>

<h2 id="Allowing-fall-through"><a id="Allowing"></a>Allowing fall-through</h2>

<p>Fall-though (trying another case after one has already succeeded) is usually a Bad Idea in a switch statement. However, this is Perl, not a police state, so there <i>is</i> a way to do it, if you must.</p>

<p>If a <code>case</code> block executes an untargeted <code>next</code>, control is immediately transferred to the statement <i>after</i> the <code>case</code> statement (i.e. usually another case), rather than out of the surrounding <code>switch</code> block.</p>

<p>For example:</p>

<pre><code>        switch ($val) {
                case 1      { handle_num_1(); next }    # and try next case...
                case &quot;1&quot;    { handle_str_1(); next }    # and try next case...
                case [0..9] { handle_num_any(); }       # and we&#39;re done
                case /\d/   { handle_dig_any(); next }  # and try next case...
                case /.*/   { handle_str_any(); next }  # and try next case...
        }</code></pre>

<p>If $val held the number <code>1</code>, the above <code>switch</code> block would call the first three <code>handle_...</code> subroutines, jumping to the next case test each time it encountered a <code>next</code>. After the third <code>case</code> block was executed, control would jump to the end of the enclosing <code>switch</code> block.</p>

<p>On the other hand, if $val held <code>10</code>, then only the last two <code>handle_...</code> subroutines would be called.</p>

<p>Note that this mechanism allows the notion of <i>conditional fall-through</i>. For example:</p>

<pre><code>        switch ($val) {
                case [0..9] { handle_num_any(); next if $val &lt; 7; }
                case /\d/   { handle_dig_any(); }
        }</code></pre>

<p>If an untargeted <code>last</code> statement is executed in a case block, this immediately transfers control out of the enclosing <code>switch</code> block (in other words, there is an implicit <code>last</code> at the end of each normal <code>case</code> block). Thus the previous example could also have been written:</p>

<pre><code>        switch ($val) {
                case [0..9] { handle_num_any(); last if $val &gt;= 7; next; }
                case /\d/   { handle_dig_any(); }
        }</code></pre>

<h2 id="Automating-fall-through"><a id="Automating"></a>Automating fall-through</h2>

<p>In situations where case fall-through should be the norm, rather than an exception, an endless succession of terminal <code>next</code>s is tedious and ugly. Hence, it is possible to reverse the default behaviour by specifying the string &quot;fallthrough&quot; when importing the module. For example, the following code is equivalent to the first example in <a href="Switch.html#Allowing-fall-through">&quot;Allowing fall-through&quot;</a>:</p>

<pre><code>        use Switch &#39;fallthrough&#39;;

        switch ($val) {
                case 1      { handle_num_1(); }
                case &quot;1&quot;    { handle_str_1(); }
                case [0..9] { handle_num_any(); last }
                case /\d/   { handle_dig_any(); }
                case /.*/   { handle_str_any(); }
        }</code></pre>

<p>Note the explicit use of a <code>last</code> to preserve the non-fall-through behaviour of the third case.</p>

<h2 id="Alternative-syntax"><a id="Alternative"></a>Alternative syntax</h2>

<p>Perl 6 will provide a built-in switch statement with essentially the same semantics as those offered by Switch.pm, but with a different pair of keywords. In Perl 6 <code>switch</code> will be spelled <code>given</code>, and <code>case</code> will be pronounced <code>when</code>. In addition, the <code>when</code> statement will not require switch or case values to be parenthesized.</p>

<p>This future syntax is also (largely) available via the Switch.pm module, by importing it with the argument <code>&quot;Perl6&quot;</code>. For example:</p>

<pre><code>        use Switch &#39;Perl6&#39;;

        given ($val) {
                when 1       { handle_num_1(); }
                when ($str1) { handle_str_1(); }
                when [0..9]  { handle_num_any(); last }
                when /\d/    { handle_dig_any(); }
                when /.*/    { handle_str_any(); }
                default      { handle anything else; }
        }</code></pre>

<p>Note that scalars still need to be parenthesized, since they would be ambiguous in Perl 5.</p>

<p>Note too that you can mix and match both syntaxes by importing the module with:</p>

<pre><code>        use Switch &#39;Perl5&#39;, &#39;Perl6&#39;;</code></pre>

<h2 id="Higher-order-Operations"><a id="Higher"></a>Higher-order Operations</h2>

<p>One situation in which <code>switch</code> and <code>case</code> do not provide a good substitute for a cascaded <code>if</code>, is where a switch value needs to be tested against a series of conditions. For example:</p>

<pre><code>        sub beverage {
            switch (shift) {
                case { $_[0] &lt; 10 } { return &#39;milk&#39; }
                case { $_[0] &lt; 20 } { return &#39;coke&#39; }
                case { $_[0] &lt; 30 } { return &#39;beer&#39; }
                case { $_[0] &lt; 40 } { return &#39;wine&#39; }
                case { $_[0] &lt; 50 } { return &#39;malt&#39; }
                case { $_[0] &lt; 60 } { return &#39;Moet&#39; }
                else                { return &#39;milk&#39; }
            }
        }</code></pre>

<p>(This is equivalent to writing <code>case (sub { $_[0] &lt; 10 })</code>, etc.; <code>$_[0]</code> is the argument to the anonymous subroutine.)</p>

<p>The need to specify each condition as a subroutine block is tiresome. To overcome this, when importing Switch.pm, a special &quot;placeholder&quot; subroutine named <code>__</code> [sic] may also be imported. This subroutine converts (almost) any expression in which it appears to a reference to a higher-order function. That is, the expression:</p>

<pre><code>        use Switch &#39;__&#39;;

        __ &lt; 2</code></pre>

<p>is equivalent to:</p>

<pre><code>        sub { $_[0] &lt; 2 }</code></pre>

<p>With <code>__</code>, the previous ugly case statements can be rewritten:</p>

<pre><code>        case  __ &lt; 10  { return &#39;milk&#39; }
        case  __ &lt; 20  { return &#39;coke&#39; }
        case  __ &lt; 30  { return &#39;beer&#39; }
        case  __ &lt; 40  { return &#39;wine&#39; }
        case  __ &lt; 50  { return &#39;malt&#39; }
        case  __ &lt; 60  { return &#39;Moet&#39; }
        else           { return &#39;milk&#39; }</code></pre>

<p>The <code>__</code> subroutine makes extensive use of operator overloading to perform its magic. All operations involving __ are overloaded to produce an anonymous subroutine that implements a lazy version of the original operation.</p>

<p>The only problem is that operator overloading does not allow the boolean operators <code>&amp;&amp;</code> and <code>||</code> to be overloaded. So a case statement like this:</p>

<pre><code>        case  0 &lt;= __ &amp;&amp; __ &lt; 10  { return &#39;digit&#39; }  </code></pre>

<p>doesn&#39;t act as expected, because when it is executed, it constructs two higher order subroutines and then treats the two resulting references as arguments to <code>&amp;&amp;</code>:</p>

<pre><code>        sub { 0 &lt;= $_[0] } &amp;&amp; sub { $_[0] &lt; 10 }</code></pre>

<p>This boolean expression is inevitably true, since both references are non-false. Fortunately, the overloaded <code>&#39;bool&#39;</code> operator catches this situation and flags it as an error.</p>

<h1 id="DEPENDENCIES">DEPENDENCIES</h1>

<p>The module is implemented using Filter::Util::Call and Text::Balanced and requires both these modules to be installed.</p>

<h1 id="AUTHOR">AUTHOR</h1>

<p>Damian Conway (damian@conway.org). This module is now maintained by Alexandr Ciornii (alexchorny@gmail.com). Previously was maintained by Rafael Garcia-Suarez and perl5 porters.</p>

<h1 id="BUGS">BUGS</h1>

<p>There are undoubtedly serious bugs lurking somewhere in code this funky :-) Bug reports and other feedback are most welcome.</p>

<p>May create syntax errors in other parts of code.</p>

<p>On perl 5.10.x may cause syntax error if &quot;case&quot; is present inside heredoc.</p>

<p>In general, use given/when instead. It were introduced in perl 5.10.0. Perl 5.10.0 was released in 2007.</p>

<h1 id="LIMITATIONS">LIMITATIONS</h1>

<p>Due to the heuristic nature of Switch.pm&#39;s source parsing, the presence of regexes with embedded newlines that are specified with raw <code>/.../</code> delimiters and don&#39;t have a modifier <code>//x</code> are indistinguishable from code chunks beginning with the division operator <code>/</code>. As a workaround you must use <code>m/.../</code> or <code>m?...?</code> for such patterns. Also, the presence of regexes specified with raw <code>?...?</code> delimiters may cause mysterious errors. The workaround is to use <code>m?...?</code> instead.</p>

<p>Due to the way source filters work in Perl, you can&#39;t use Switch inside an string <code>eval</code>.</p>

<p>May not work if sub prototypes are used (RT#33988).</p>

<p>Regex captures in when are not available to code.</p>

<p>If your source file is longer then 1 million characters and you have a switch statement that crosses the 1 million (or 2 million, etc.) character boundary you will get mysterious errors. The workaround is to use smaller source files.</p>

<h1 id="COPYRIGHT">COPYRIGHT</h1>

<pre><code>    Copyright (c) 1997-2008, Damian Conway. All Rights Reserved.
    This module is free software. It may be used, redistributed
        and/or modified under the same terms as Perl itself.</code></pre></div>

<div id="metacpan_install-instructions-dialog" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Module Install Instructions</h4>
      </div>
      <div class="modal-body">
        <p>To install Switch, copy and paste the appropriate command in to your terminal.</p>
        <p><a href="https://metacpan.org/dist/App-cpanminus/view/bin/cpanm">cpanm</a></p>
        <pre><code>cpanm Switch</code></pre>
        <p><a href="https://metacpan.org/pod/CPAN">CPAN shell</a></p>
        <pre><code>perl -MCPAN -e shell
install Switch</code></pre>
        <p>For more information on module installation, please visit <a href="https://www.cpan.org/modules/INSTALL.html">the detailed CPAN module installation guide</a>.</p>
      </div>
      <div class="modal-footer">
        <a href="Switch.html#" data-dismiss="modal" class="btn">Close</a>
      </div>
    </div>
  </div>
</div>
          </main>
          <div class="content-pagination">
          </div>
        </div>
        <footer class="footer">
          <div class="footer-container">
            <div class="footer-social">
              <div class="footer-link footer-logo">
                <a href="https://metacpan.org/">
                  <img src="https://metacpan.org/static/images/metacpan-logo.svg" alt="MetaCPAN" />
                </a>
              </div>
              <a class="footer-social-link" href="https://github.com/metacpan">
                <i class="fab fa-github-square"></i>
              </a>
              <a class="footer-social-link" href="https://fosstodon.org/@metacpan">
                <i class="fab fa-mastodon"></i>
              </a>
            </div>
            <div class="footer-links">
              <div class="footer-link">
                  <a href="https://metacpan.org/about">About</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/sponsors">Sponsor</a>
              </div>
              <div class="footer-link">
                  <a href="https://grep.metacpan.org">grep::cpan</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/recent">Recent</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/faq">FAQ</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/tools">Tools</a>
              </div>
              <div class="footer-link">
                  <a href="https://fastapi.metacpan.org/">API</a>
              </div>
              <div class="footer-link">
                  <a href="https://www.perl.org/">Perl.org</a>
              </div>
            </div>
            <div class="footer-sponsors">
              <a class="footer-sponsor-link" target="_blank" href="https://www.bytemark.co.uk/" rel="noopener">
                <img class="footer-sponsor-bytemark" src="https://metacpan.org/static/images/sponsors/bytemark_logo.svg" alt="Bytemark logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.liquidweb.com/" rel="noopener">
                <img class="footer-sponsor-liquidweb" src="https://metacpan.org/static/images/sponsors/liquidweb_logo.png" alt="liquidweb logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://deriv.com/careers/" rel="noopener">
                <img class="footer-sponsor-deriv" src="https://metacpan.org/static/images/sponsors/deriv.svg" alt="Deriv logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://geocode.xyz" rel="noopener">
                <img class="footer-sponsor-geocode" src="https://metacpan.org/static/images/sponsors/geocodelogo.svg" alt="Geocode logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.fastly.com/" rel="noopener">
                <img class="footer-sponsor-fastly" src="https://metacpan.org/static/images/sponsors/fastly_logo.svg" alt="Fastly logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://opencagedata.com" rel="noopener">
                <img class="footer-sponsor-opencage" src="https://metacpan.org/static/images/sponsors/open-cage.svg" alt="OpenCage logo">
              </a>
            </div>
          </div>
        </footer>
        <div class="modal fade" tabindex="-1" role="dialog" id="metacpan_keyboard-shortcuts">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Keyboard Shortcuts</h4>
              </div>
              <div class="modal-body row">
<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Global</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>s</kbd>
        </td>
        <td>Focus search bar</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>?</kbd>
        </td>
        <td>Bring up this help dialog</td>
      </tr>
    </tbody>
  </table>

  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>GitHub</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>p</kbd>
        </td>
        <td>Go to pull requests</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>go to github issues (only if github is preferred repository)</td>
      </tr>
    </tbody>
  </table>
</div>

<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>POD</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>a</kbd>
        </td>
        <td>Go to author</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>c</kbd>
        </td>
        <td>Go to changes</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>Go to issues</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>d</kbd>
        </td>
        <td>Go to dist</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>r</kbd>
        </td>
        <td>Go to repository/SCM</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>s</kbd>
        </td>
        <td>Go to source</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>b</kbd>
        </td>
        <td>Go to file browse</td>
      </tr>

    </tbody>
  </table>
</div>

<div class="col-md-12">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Search terms</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><em>module:</em> (e.g. <a href="https://metacpan.org/search?q=module%3APlugin">module:Plugin</a>)</td>
      </tr>
      <tr>
        <td><em>distribution:</em> (e.g. <a href="https://metacpan.org/search?q=distribution%3ADancer+auth">distribution:Dancer auth</a>)</td>
      </tr>
      <tr>
        <td><em>author:</em> (e.g. <a href="https://metacpan.org/search?q=author%3ASONGMU+Redis">author:SONGMU Redis</a>)</td>
      </tr>
      <tr>
        <td><em>version:</em> (e.g. <a href="https://metacpan.org/search?q=version%3A1.00">version:1.00</a>)</td>
      </tr>
    </tbody>
  </table>
</div>
              </div>
              <div class="modal-footer"></div>
            </div>
          </div>
        </div>
    </body>
</html>
